<template>
  <div>
    <h1>公告管理</h1>
    <div class="ring_bg">
      <div class="notice_list_class" style="width: calc(40% - 30px); float: left; border-right:1px solid #EBEEF3;">
        <div style="background: #fff;height:30px; padding-bottom: 20px;border-bottom: 1px solid #EBEEF3;">
          <span>公告列表</span>
          <el-button type="primary" @click="publicNotice" style="float: right;margin-right: 20px"><i
              class="el-icon-s-promotion"></i>&nbsp;&nbsp;发布公告
          </el-button>
        </div>
        <div style="height: 450px; overflow: auto;">
          <ul style="display: inline-block;width:95%">
            <li v-for="i in rows" style="border-bottom:1px solid #EBEEF3;height:100px;padding:20px 0"
                @click="showNotice(i)">
              <div style="font-size: 12px;"><i class="el-icon-message-solid"
                                               style="color: #5B73FF;margin-right:10px;"></i><span
                  style="color: #5a618b;">系统消息</span>
                <span style="float:right;color: #5a618b;">{{i.distanceTime}}</span>
                <el-button size="mini" plain disabled round v-if="!i.isRead" type="danger" style="margin-left: 10px">未读</el-button>
              </div>
              <div style="font-size: 18px;font-weight: bold;margin: 10px 0 10px 22px;">{{ i.title }}</div>
              <div style="font-size: 14px;margin-left:22px;color: #5a618b;">{{ i.content }}</div>
            </li>
          </ul>
        </div>
        <el-drawer title="发布公告" :before-close="handleClose" :visible.sync="dialog" v-if="dialog"
                   direction="rtl" ref="drawer" size="40%;">
          <div style="position: relative;width: 100%">
            <el-form :model="form" ref="ruleForm" :rules="rules">
              <el-form-item label="发送对象：" prop="title" label-width="80px">
                <el-radio-group v-model="form.userType">
                  <el-radio label="02">发送至商户</el-radio>
                  <el-radio label="01">发送至业务人员</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="公告标题：" prop="title" label-width="80px">
                <el-input v-model="form.title"></el-input>
              </el-form-item>
              <el-form-item label="公告内容：" prop="content" label-width="80px">
                <el-input type="textarea" :rows="25" maxlength="500" show-word-limit v-model="form.content"></el-input>
              </el-form-item>
            </el-form>
            <div
                style="text-align: center;position: fixed;bottom: 0;width:40% ;background: #fff;height: 70px;right: 0;display: flex;justify-content: center;align-items: center;">
              <el-button type="danger" @click="dialog = false" style="height: 30px">取 消</el-button>
              <el-button type="primary" @click="saveNovice" :loading="loading" style="height: 30px">
                {{ loading ? '提交中 ...' : '确 定' }}
              </el-button>
            </div>
          </div>
        </el-drawer>
      </div>
      <div style="width: 60%;float: left;">
        <div style="padding: 0 0 0 20px ;">
          <div style="color:#b2b6cd;font-size: 12px;"><span>{{ notice.createTime }}</span><span
              style="margin-left: 30px;float: right">{{ notice.createUserName }}</span></div>
          <div v-html="notice.title"
               style="font-size: 22px;margin-bottom: 10px;margin-top: 10px;font-weight: bold"></div>
          <div v-html="notice.htmlContent"
               style="font-size: 14px;color: #4d5176;background: #fafafa;padding: 10px;height: 420px;overflow: auto;"></div>
        </div>
      </div>
    </div>
  </div>

</template>

<script>
import request from "@/utils/Request";

export default {
  name: "NoticeManager",
  data() {
    return {
      count: 10,
      rows: [],
      total: 0,
      clientHeight: window.innerHeight - 70 + 'px',
      form: {
        title: '',
        content: '',
      },
      notice: {},
      rules: {
        title: [
          {required: true, message: '请输入公告标题', trigger: 'blur'},
        ],
        content: [
          {required: true, message: '请输入公告内容', trigger: 'blur'}
        ],
      },
      dialog: false,
      showNoticeDialog: false,
      loading: false,
      queryParam: {pageSize: 10, pageNo: 1}
    }
  },
  mounted() {
    this.init();
    document.addEventListener('scroll', this.scrollLoad, true);
  },
  methods: {
    publicNotice() {
      this.form = {userType: '02'};
      this.dialog = true
    },
    showNotice(notice) {
      this.notice = notice;
      this.notice.htmlContent = this.notice.content;
      this.notice.htmlContent = this.notice.htmlContent.replace(/\n/g, '<br/>');
      this.notice.htmlContent = this.notice.htmlContent.replace(/ /g, ' &nbsp');
      if (!notice.isRead) {
        request.post("/notice/read", {noticeId:notice.id}).then(({data})=>{
          if (data.success) {
            notice.isRead = true;
          }
        }).catch(err => {
          this.$message({type: 'error', message: "标记已读失败"});
          console.log(err)
        })
      }
      // this.showNoticeDialog = true;
    },
    init() {
      request.get("/notice/list", {params: this.queryParam}).then(({data}) => {
        if (data.success) {
          this.rows.push(...data.data.rows);
          this.total = data.data.total;
          //计算时间差
          this.rows.forEach(i => {
            const createTime = new Date(i.createTime);
            const now = new Date()
            let day = (now - createTime) / (24 * 60 * 60 * 1000);
            let month = parseInt(day / 30);
            if (day >= 365) {
              i.distanceTime = '1年前'
            } else if (month >= 1 && month <= 12) {
              i.distanceTime = `${month}个月前`
            } else if (day < 30 && day >= 1) {
              i.distanceTime = `${parseInt(day)}天前`;
            } else if (day >= 0.0416) {
              i.distanceTime = `${parseInt(day * 24)}小时前`;
            } else if (day >= 0.00347 && day < 0.0416) {
              i.distanceTime = `${parseInt(day * 24 * 60)}分钟前`;
            } else {
              i.distanceTime = '刚刚';
            }
          })
        } else {
          throw new Error()
        }
      }).catch(err => {
        this.$message({type: 'error', message: "查询公告失败"});
        console.log(err)
      })
    },
    async saveNovice() {
      const confirm = await this.$confirm('是否确认发布公告?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return true;
      }).catch(() => {
        return false;
      });
      if (!confirm) {
        return;
      }
      this.loading = true;
      const validate = await new Promise((resolve, reject) => {
        this.$refs.ruleForm.validate((v) => {
          resolve(v);
        })
      })
      if (validate) {
        request.post("/notice/save", this.form).then(({data}) => {
          if (data.success) {
            this.$message({type: 'success', message: '发布公告成功'});
            this.rows = [];
            this.init();
          } else {
            this.$message({type: 'warning', message: data.message});
          }
        }).catch(err => {
          this.$message({type: 'error', message: "保存公告失败"});
          console.log(err)
        }).finally(() => {
          this.dialog = false;
          this.loading = false;
        })
      }
    },
    handleClose(done) {
      this.dialog = false;
    },
    scrollLoad() {
      if (this.$route.path === '/NoticeManager') {
        let scrollbar = document.querySelector('.notice_list_class');
        let scrollHeight = scrollbar.scrollHeight || document.body.scrollHeight; //document的滚动高度
        let clientHeight = scrollbar.clientHeight || document.body.clientHeight;  //可视区高度
        let scrollTop = scrollbar.scrollTop || document.body.scrollTop || window.pageYOffset; //已滚动高度
        if (!this.onFetching) {
          if (clientHeight >= scrollHeight - scrollTop - 20) {
            this.onFetching = true
            this.queryParam.pageNo += 1;
            this.init();
          }
        }
      }
    }
  }
}
</script>

<style scoped>
.ring_bg {
  padding: 20px;
  background: #fff;
  border-radius: 3px;
  border: 1px solid #EBEEF3;
  margin-top: 20px;
  height: 500px;
}
</style>